package com.lyq.blog.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtUtil {
    private static final long EXPIRE_DATE = 24*60*60*1000;
    private static final Key KEY = Keys.hmacShaKeyFor(Decoders.BASE64.decode("KUnCin3MtX3gYHKv6s0ArTyQ3w5FUCRZ4sCeziigf5E="));

    //生成令牌
    public static String creatToken(Map<String, Object> map) {
        return Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRE_DATE))
                .signWith(KEY)
                .compact();
    }

    //解析token
    public static Claims parserToken(String token) {
        JwtParser build = Jwts.parserBuilder().setSigningKey(KEY).build();
        Claims body = null;
        try{
            body = build.parseClaimsJws(token).getBody();
        }catch (ExpiredJwtException e) {
            log.error("token 超时过期 token:{}", token);
        }catch (Exception e) {
            log.error("token 校验失败 token:{}", token);
        }
        return body;
    }
}
